#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Create Time    : 2024/8/27 15:16
# @File           : parse_need
# @IDE            : PyCharm
# @desc           : 从工单文字描述中解析出辅料资源需求和外协班组

import re
from application.settings import CONFIG


class TicketParser:
    def __init__(self, ticket, rule):
        self.ticket = ticket
        self.rule = rule
        self.priority_config = CONFIG.DISPATCH.TASK_TYPE_PRIORITY
    
    @property
    def ticket_id(self):
        return self.ticket['ticket_id']
    
    @property
    def product_type(self):
        return self.ticket['product_type']
    
    @property
    def flight(self):
        return self.ticket['flight']
    
    @property
    def ticket_work_infos(self):
        return self.ticket.get("work_infos", []) or []

    @property
    def parse_team_rules(self):
        return [i for i in self.rule if i['rule_type'] == '外协匹配']
    
    @property
    def parse_needs_rules(self):
        return [i for i in self.rule if i['rule_type'] == '辅料提取']

    @property
    def ticket_pi(self):
        tag = False
        for i in self.ticket_work_infos:
            pi = i.get("pi")
            if isinstance(pi, int):
                tag = bool(pi)
            elif isinstance(pi, bool):
                tag = pi
            elif isinstance(pi, list):
                tag = [j for j in pi if j['status']]
            if tag:
                return True
        return False
    
    @property
    def ticket_priority(self):
        p = [i['priority'] for i in self.priority_config if i['type'] == self.ticket.get("ao_type", "AO")]
        return min(p) if p else 99

    def _match_need_rule(self, need_rule, workinfo):
        needs = []
        for rule in need_rule['rules']:
            field_content = workinfo.get(rule['field'], "")
            matches = re.finditer(rule['pattern'].strip('/'), str(field_content), flags=re.RegexFlag.I)
            for match in matches:
                if not match:
                    continue
                need = match.groupdict()
                if need and need not in needs:
                    needs.append(need)
        return list(needs)

    def parse_needs(self):
        needs = []
        for workinfo in self.ticket_work_infos:
            for need_rule in self.parse_needs_rules:
                need = self._match_need_rule(need_rule, workinfo)
                if not need:
                    continue
                needs.extend(need)
        return needs
        
    def _match_team_rule(self, team_rule, workinfo):
        for rule in team_rule['rules']:
            field_content = workinfo.get(rule['field'], "")
            match = re.search(rule['pattern'].strip('/'), str(field_content), flags=re.RegexFlag.I)
            if not match:
                return None
        return {
            "work_no": workinfo.get("work_no"),
            "work_title": workinfo.get("title"),
            "work_start": workinfo.get("start"),
            "name": team_rule['rule_name']
        }

    def parse_teams(self):
        teams = []
        for workinfo in self.ticket_work_infos:
            for team_rule in self.parse_team_rules:
                team = self._match_team_rule(team_rule, workinfo)
                if not team:
                    continue
                teams.append(team)
        return teams

    def dumps(self):
        data = {key:value for key, value in self.ticket.items()}
        if 'work_infos' in data:
            del data['work_infos']
        data['work_teams'] = self.parse_teams()
        data['pi'] = bool(self.ticket_pi)
        data['supplementary_needs'] = self.parse_needs()
        data['priority'] = self.ticket_priority
        return data
    